#define  _CRT_SECURE_NO_WARNINGS 1
#include"Queue.h"
//

//队列的初始化
void QueueInit(Queue* pq)
{
	assert(pq);
	pq->phead = pq->ptail = NULL;
}

//入队(自己写的，未优化）
//void QueuePush(Queue* pq, QDatatype x)
//{
//	assert(pq);
//	if (pq->phead == NULL)
//	{
//		pq->phead = pq->ptail = (QueueNode*)malloc(sizeof(QueueNode));
//		pq->phead->data = x;
//		pq->phead->next = NULL;
//	}
//	else {
//		pq->ptail->next = (QueueNode*)malloc(sizeof(QueueNode));
//		pq->ptail = pq->ptail->next;
//		pq->ptail->data = x;
//		pq->ptail->next = NULL;
//	}
//}

//入队（优化后）
void QueuePush(Queue* pq, QDatatype x)
{
	assert(pq);
	QueueNode* newnode = (QueueNode*)malloc(sizeof(QueueNode));
	if (newnode == NULL)
	{
		perror("malloc fail!\n");
		exit(1);
	}
	newnode->data = x;
	newnode->next = NULL;

	//队列为空，队头和队尾都是newnode
	if (pq->phead == NULL)
	{
		pq->phead = pq->ptail = newnode;
	}
	else {
		//pq->ptail newnode
		pq->ptail->next = newnode;
		pq->ptail = pq->ptail->next;
	}
}

//判断队列是否为空
bool QueueEmpty(Queue* pq)
{
	assert(pq);
	return pq->phead == NULL;
}

//出队
void QueuePop(Queue* pq)
{
	assert(!QueueEmpty(pq));
	if (pq->phead == pq->ptail)
	{
		free(pq->phead);
		pq->phead = pq->ptail = NULL;
	}
	else {
		QueueNode* next = pq->phead->next;
		free(pq->phead);
		pq->phead = next;
	}
}

//取队头数据
QDatatype QueueFront(Queue* pq)
{
	assert(!QueueEmpty(pq));
	return pq->phead->data;
}

//取队尾数据
QDatatype QueueBack(Queue* pq)
{
	assert(pq);
	assert(!QueueEmpty(pq));
	return pq->ptail->data;
}

void QueueDestory(Queue* pq)
{
	assert(pq);
	while (pq->phead)
	{
		QueueNode* next = pq->phead->next;
		free(pq->phead);
		pq->phead = next;
	}
	pq->phead = pq->ptail = NULL;
}

//队列有效个数
int QueueSize(Queue* pq)
{
	int size = 0;
	QueueNode* pcur = pq->phead;
	while (pcur)
	{
		size++;
		pcur = pcur->next;
	}
	return size;

	
}